package com.huanxing.cloud.order.event.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huanxing.cloud.common.core.constant.CommonConstants;
import com.huanxing.cloud.order.api.entity.OrderInfo;
import com.huanxing.cloud.order.api.entity.OrderItem;
import com.huanxing.cloud.order.api.entity.OrderRefund;
import com.huanxing.cloud.order.api.enums.OrderItemEnum;
import com.huanxing.cloud.order.api.enums.OrderRefundEnum;
import com.huanxing.cloud.order.api.enums.OrderStatusEnum;
import com.huanxing.cloud.order.event.HxOrderRefundEvent;
import com.huanxing.cloud.order.service.IOrderInfoService;
import com.huanxing.cloud.order.service.IOrderItemService;
import com.huanxing.cloud.order.service.IOrderRefundService;
import com.huanxing.cloud.product.api.dto.GoodsSkuStockReqDTO;
import com.huanxing.cloud.product.api.remote.RemoteGoodsSkuService;
import com.huanxing.cloud.promotion.api.dto.CouponUserReqDTO;
import com.huanxing.cloud.promotion.api.enums.CouponUserStatusEnum;
import com.huanxing.cloud.promotion.api.remote.RemoteCouponUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author: lijx
 * @date: 2023/4/24 11:57
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class HxOrderRefundEventListener {

	private final IOrderRefundService orderRefundService;

	private final IOrderItemService orderItemService;

	@DubboReference
	private final RemoteGoodsSkuService remoteGoodsSkuService;

	private final IOrderInfoService orderInfoService;

	@DubboReference
	private final RemoteCouponUserService remoteCouponUserService;

	/**
	 * 退款单（退款是否到账）状态更改
	 * @param event
	 */
	@EventListener(HxOrderRefundEvent.class)
	public void refundStatusEventListener(HxOrderRefundEvent event) {
		// 退款单信息
		final OrderRefund orderRefund = event.getOrderRefund();
		if (null == orderRefund) {
			log.warn("orderRefund not found!");
			return;
		}
		orderRefund.setArrivalStatus(CommonConstants.YES);
		orderRefundService.updateById(orderRefund);
	}

	/**
	 * 回滚商品库存
	 * @param event
	 */
	@EventListener(HxOrderRefundEvent.class)
	public void stockEventListener(HxOrderRefundEvent event) {
		// 退款单信息
		final OrderRefund orderRefund = event.getOrderRefund();
		if (null == orderRefund) {
			log.warn("orderRefund not found!");
			return;
		}
		if (!OrderRefundEnum.STATUS_12.getCode().equals(orderRefund.getStatus())) {
			return;
		}
		final OrderItem orderItem = event.getOrderItem();
		GoodsSkuStockReqDTO goodsSkuStockRqDTO = new GoodsSkuStockReqDTO();
		goodsSkuStockRqDTO.setStockNum(orderItem.getBuyQuantity());
		goodsSkuStockRqDTO.setSkuId(orderItem.getSkuId());
		List<GoodsSkuStockReqDTO> goodsSkuStockRqDTOList = new ArrayList<>();
		goodsSkuStockRqDTOList.add(goodsSkuStockRqDTO);
		remoteGoodsSkuService.rollbackStock(goodsSkuStockRqDTOList);
	}

	/**
	 * 订单状态更改
	 * @param event
	 */
	@EventListener(HxOrderRefundEvent.class)
	public void orderStatusEventListener(HxOrderRefundEvent event) {
		// 退款单信息
		final OrderRefund orderRefund = event.getOrderRefund();
		if (null == orderRefund) {
			log.warn("orderRefund not found!");
			return;
		}
		OrderItem orderItem = event.getOrderItem();
		orderItem.setIsRefund(CommonConstants.YES);
		orderItem.setStatus(OrderRefundEnum.STATUS_11.getCode().equals(orderRefund.getStatus())
				? OrderItemEnum.SUCCESS_REFUND.getStatus()
				: OrderRefundEnum.STATUS_12.getCode().equals(orderRefund.getStatus())
						? OrderItemEnum.SUCCESS_GOODS_REFUND.getStatus() : "");
		orderItemService.updateById(orderItem);

		// 查询所有子订单
		List<OrderItem> orderItemList = orderItemService
			.list(Wrappers.<OrderItem>lambdaQuery().eq(OrderItem::getOrderId, orderRefund.getOrderId()))
			.stream()
			.filter(orderItem1 -> !orderItem1.getId().equals(orderItem.getId())
					&& CommonConstants.NO.equals(orderItem1.getIsRefund()))
			.toList();

		// 判断是否全部完成退款
		if (CollectionUtils.isEmpty(orderItemList)) {
			// 取消订单
			OrderInfo orderInfo = new OrderInfo();
			orderInfo.setId(orderRefund.getOrderId());
			orderInfo.setStatus(OrderStatusEnum.STATUS_11.getCode());
			orderInfoService.updateById(orderInfo);
		}
	}

	/**
	 * 回滚优惠券
	 * @param event
	 */
	@EventListener(HxOrderRefundEvent.class)
	public void couponEventListener(HxOrderRefundEvent event) {
		// 退款单信息
		final OrderRefund orderRefund = event.getOrderRefund();
		if (null == orderRefund) {
			log.warn("orderRefund not found!");
			return;
		}
		// 查询订单
		OrderInfo orderInfo = orderInfoService.getById(orderRefund.getOrderId());
		if (Objects.isNull(orderInfo)) {
			log.warn("orderInfo not found!");
			return;
		}
		if (!StringUtils.hasText(orderInfo.getCouponUserId())) {
			return;
		}
		// 调用优惠券服务接口回滚优惠券
		CouponUserReqDTO couponUserReqDTO = new CouponUserReqDTO();
		couponUserReqDTO.setId(orderInfo.getCouponUserId());
		couponUserReqDTO.setCouponUserStatusEnum(CouponUserStatusEnum.STATUS_0);
		remoteCouponUserService.updateCouponUserStatus(couponUserReqDTO);
	}

}
